package com.bw.mvvm_common.network.inteceptor;

import android.util.Log;

import com.bw.mvvm_common.utils.SignUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Iterator;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

public class SignInterceptor implements Interceptor {

    /**
     * 服务器接口参数不固定
     * 获取Request
     * 新建Request
     * 原有Request url以及header复制到新的request中
     * 获取原有request body
     * 获取body 中json 字符串
     * JSONObject 解析
     * 获取json下对应value
     * value生成sign
     * 生成新的json
     * 创建body
     * 添加到request中
     * */
    @Override
    public Response intercept(Chain chain) throws IOException {
        //{"imie":"1"}
        Request oldRequest = chain.request();
        Request.Builder builder = new Request.Builder();
        builder.url(oldRequest.url());
        builder.headers(oldRequest.headers());
        RequestBody body = oldRequest.body();
        if (body == null)
            return chain.proceed(oldRequest);
        Buffer buf = new Buffer();
        body.writeTo(buf);
        byte[]buff = new byte[1024];
        String json = "";
        while (buf.read(buff)!=-1){
            json +=new String(buff);
        }
        buf.flush();
        buf.close();
        //{"imie":"1"}
        String value = "";
        String result = "";
        try {
            JSONObject job = new JSONObject(json);
            Iterator<String>it = job.keys();
            while (it.hasNext()){
                value += job.getString(it.next());
            }
            //value=1
            String sign = SignUtils.createSign(value);
            job.put("sign",sign);
            result = job.toString();
            Log.e("ZXY","Sign:"+result);
            //{"imie":"1","sign":"516576e2bb29311613600ddaaf8fb83f"}
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),result);
        builder.post(requestBody);
        //{"imie":"1","sign":"516576e2bb29311613600ddaaf8fb83f"}
        return chain.proceed(builder.build());
    }
}
